package com.bnz.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnz.user.dao.UserMapper;
import com.bnz.user.entity.User;
import com.bnz.user.service.UserService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate mqTemplate;
    /**
     * 使用手机号发送验证码进行注册
     * @param phone
     */
    @Override
    public void sendSms(String phone) {
        //1. 首先生成一个四位验证码
        String code = RandomUtil.randomNumbers(4);
        //2. 将验证码存入redis中并且有效期为15分钟
        redisTemplate.opsForValue().set(phone, code, 15, TimeUnit.MINUTES);
        //3. 利用rocketmq将手机号与验证码发送出去
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("code", code);
        map.put("code", JSON.toJSONString(codeMap));
        //3.1 通过中间件发送出去
        mqTemplate.convertAndSend("sms", map);
    }

    //2. 验证码的合法性
    @Override
    public boolean isExistCode(String phone, String code) {
        //2.1 从redis中取得验证码
        String codeRedis = redisTemplate.opsForValue().get(phone);
        //2.2 比较两次的验证码是否一致
        return code.equals(codeRedis);
    }

    // 3.添加用户
    @Override
    public void add(User user) {
        // 3.1 得到加密后的密码
        String password = SecureUtil.md5(user.getPassword());
        // 3.2 设置用户
        user.setPassword(password);
        // 3.3 保存用户
        this.save(user);

    }


}
